package com.cosina.game.robodefence.model;

import java.util.Observable;

import android.graphics.Point;
import android.view.View;

import com.cosina.game.robodefence.core.BattleEngine;
import com.cosina.game.robodefence.core.BattleField;
import com.cosina.game.robodefence.dao.TowerDao;
import com.cosina.game.robodefence.data.TowerData;


public class Finger extends Observable{
	
	public static Point dot = new Point(-1,-1);
	public static int kind = -1 ;
	
	static enum Status {
		NONE, Updating, BUYING;
	}
	
	public static boolean fieldCanBuilder = false;
	private static Status operation = Status.NONE;
	
	
	public static void attach(int x, int y, int kind){
		dot.set(x, y);
		
		Finger.kind = kind;
		set(Status.BUYING);
		updateCanBuilder();
	}
	
	
	public  static View listenerView;
	
	public static void set(Status status){
		if(Finger.operation == status){
			return ;
		}
		Finger.operation = status;
		listenerView.postInvalidate();
	}
	
	public static void clear(){
		dot.set(-1, -1);
		kind = -1;
		fieldCanBuilder = false;
		set(Status.NONE);
	}
	
	public static boolean isClean(){
		return operation == Status.NONE;
	}
	
	public static boolean isBuying(){
		return operation == Status.BUYING;
	}
	
	public static boolean isUpdating(){
		return operation == Status.Updating;
	}
	
	private static void updateCanBuilder(){
		fieldCanBuilder = BattleEngine.field.checkCanBuilder(dot.x, dot.y);
	}

	public static void update(int x2, int y2) {
		if(dot.equals(x2, y2)){
			return ;
		}
		dot.set(x2, y2);
		updateCanBuilder();
	}

	public static void tryBuyAndclear() {
		if(fieldCanBuilder){
			BattleEngine.commander.use(TowerDao.getUpgradeCost(kind));
			BattleEngine.field.build(dot.x, dot.y, kind);
		}
		clear();
	}

	public static void tryUpdate(int kind) {
		BattleField field = BattleEngine.field;
		if(kind == TowerData.SELL){
			field.demolition(dot.x, dot.y);
			BattleEngine.commander.get(TowerDao.getSellMoney(Finger.kind));
			clear();
		} else{
			field.buildUp(dot.x, dot.y,kind);
			BattleEngine.commander.use(TowerDao.getUpgradeCost(Finger.kind));
			Finger.kind = kind;
		}
	}

	public static void select(int tileX, int tileY, int i) {
		clear();
		dot.set(tileX, tileY);
		kind = i;
		set(Status.Updating);
	}

	public static void releaseSelect() {
		clear();
	}
}
